from flask.views import MethodView
from flask import jsonify, request, session
from werkzeug.security import check_password_hash, generate_password_hash
from app.extensions import db
from app.dbmodel import UserInfo
from flask import current_app
import csv
import os
import json
from datetime import datetime

#
#       验证用户登录信息
#           POST方法
#用户登录   /auth/userAuth/login
#用户登出   /auth/userAuth/logout
#用户注册   /auth/userAuth/register
#           DELETE方法
# 删除用户   /auth/userAuth/


class Auth(MethodView):

    __methods__ = ["GET", "POST", "DELETE"]

    def post(self, action):   # action为login, logout, register之一, 分别为登录、登出、注册

        if action == 'login':
            username = request.form.get('username')
            password = request.form.get('password')
            user_info = UserInfo.query.filter_by(username=username).first()
            if check_password_hash(user_info.password, password):
                session.clear()
                session['user_id'] = user_info.id   # 登录成功，则将用户user_id写入session
            return jsonify({"code": "0", "status": "0", "result": "this ok"})

        if action == 'logout':
            pass

        if action == 'register':
            username = request.form.get('username')
            password = request.form.get('password')
            if not UserInfo.query.filter_by(username=username).first():
                user_info = UserInfo(
                    username=username, password=generate_password_hash(password))
                db.session.add(user_info)
                db.session.commit()
                count = UserInfo.query.count()
                if UserInfo.query.get(count) == UserInfo:
                    print(f'{username}注册成功')
                    return jsonify({"code": "0", "status": "0", "result": "this ok"})
            else:
                print(f'{username}注册失败, 用户可能已存在')
                return jsonify({"code": "1", "status": "1", "result": "error"})
